<template>
  <el-form
      ref="ruleFormRef"
      :model="user"
      :rules="rules"
      label-width="120px"
      class="demo-ruleForm"
      :size="formSize"
  >
    <el-form-item label="username" prop="username">
      <el-input v-model="user.username"></el-input>
    </el-form-item>
    <el-form-item label="password" prop="password">
      <el-input autocomplete="off" type="password" v-model="user.password"></el-input>
    </el-form-item>
    <el-form-item label="phone" prop="phone">
      <el-input v-model="user.phone"></el-input>
    </el-form-item>
    <el-form-item label="email" prop="email">
      <el-input v-model="user.email"></el-input>
    </el-form-item>

    <el-form-item label="position" prop="position">
      <el-radio-group v-model="user.position">
        <el-radio label="crowd"></el-radio>
        <el-radio label="publisher"></el-radio>
        <el-radio label="admin"></el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)"
      >Create
      </el-button
      >
      <el-button @click="resetForm(ruleFormRef)">Reset</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import {reactive, ref} from 'vue'
import type {ElForm} from 'element-plus'
import register from "@/api/user/register";
// import register from "@/api/user/register";

type FormInstance = InstanceType<typeof ElForm>

const formSize = ref('')
const ruleFormRef = ref<FormInstance>()
const user = reactive({
  id: -1,
  username: '',
  password: '',
  phone: '',
  email: '',
  position: '',

})

const rules = reactive({
  username: [
    {
      required: true,
      message: 'Please input username',
      trigger: 'blur',
    }, {
      min: 4,
      max: 25,
      message: 'Length should be 4 to 25',
      trigger: 'blur',
    }
  ],
  password: [
    {
      required: true,
      message: 'Please input password',
      trigger: 'blur'
    },
    {
      min: 6,
      max: 25,
      message: 'Length should be 4 to 25',
      trigger: 'blur',
    }
  ],
  phone: [
    {
      required: true,
      message: 'Please input phone',
      trigger: 'blur'
    },
    {
      min: 8,
      max: 11,
      message: 'Length should be 8 to 11',
      trigger: 'blur',
    }
  ],
  email: [
    {
      required: true,
      message: 'Please input email',
      trigger: 'blur'
    }
  ],
  position: [
    {
      required: true
    }
  ]
})

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      console.log('register!')
      register(user);


    } else {
      console.log('error submit!')
      return false
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>

<style scoped>

</style>